package com.mcp.converter.domain.rule.conversion.datatype;

import com.mcp.converter.domain.rule.conversion.ConversionRule;
import com.mcp.converter.shared.enums.IncompatibilityType;
import com.mcp.converter.shared.enums.SQLElementType;
import com.mcp.converter.domain.converter.ConversionSuggestion;
import com.mcp.converter.shared.response.sql.SQLElement;

/**
 * NCLOB数据类型转换规则
 * 将NCLOB数据类型转换为CLOB数据类型
 * @author zengxiong
 */
public class NClobToClobConversionRule implements ConversionRule {

    private static final String RULE_ID = "CV_DT004";
    private static final String RULE_NAME = "NCLOB转CLOB";
    private static final String RULE_DESCRIPTION = "将NCLOB数据类型转换为CLOB数据类型。确保目标CLOB列使用支持Unicode的字符集（如UTF-8）。";

    private ConversionSuggestion conversionSuggestion;

    public NClobToClobConversionRule() {
        this.conversionSuggestion = new ConversionSuggestion();
        this.conversionSuggestion.setSuggestion("将NCLOB数据类型替换为CLOB数据类型。建议数据库或表级别使用UTF-8字符集。");
        this.conversionSuggestion.setExample("CREATE TABLE example (text_data NCLOB) -> CREATE TABLE example (text_data CLOB)");
        this.conversionSuggestion.setAutoConvertible(true);
        this.conversionSuggestion.setComplexity(ConversionSuggestion.Complexity.SIMPLE); // Direct type replacement, character set is a configuration concern
    }

    @Override
    public String getId() {
        return RULE_ID;
    }

    @Override
    public String getName() {
        return RULE_NAME;
    }

    @Override
    public String getDescription() {
        return RULE_DESCRIPTION;
    }

    @Override
    public IncompatibilityType getIncompatibilityType() {
        return IncompatibilityType.DATA_TYPE;
    }

    @Override
    public ConversionSuggestion getConversionSuggestion() {
        return conversionSuggestion;
    }

    @Override
    public boolean matches(Object target) {
        if (target instanceof SQLElement) {
            SQLElement element = (SQLElement) target;
            if (element.getType() == SQLElementType.DATA_TYPE) {
                String dataTypeName = element.getName() != null ? element.getName().toUpperCase() : (element.getValue() != null ? element.getValue().toUpperCase() : "");
                return "NCLOB".equals(dataTypeName) || "NATIONAL CHARACTER LARGE OBJECT".equals(dataTypeName);
            }
        }
        return false;
    }

    @Override
    public String convert(SQLElement element, ConversionContext context) {
        String original = element.getValue() != null ? element.getValue() : "NCLOB";
        String converted = "CLOB";

        if (context != null) {
            context.addConversionDetail(original, converted, "NCLOB数据类型在OceanBase中不支持，已转换为CLOB。请确保数据库/表使用UTF-8等Unicode字符集。");
        }
        
        return converted;
    }
}
